﻿using Furion.JsonSerialization;
using Furion.Logging;

namespace Kyx.Core.EventSubscribers;

/// <summary>
/// 数据库日志写入器
/// </summary>
public class DbLoggingWriter : IDatabaseLoggingWriter
{
    private readonly IRepository<SysLogOp> _sysLogOpRep; // 操作日志
    private readonly IRepository<SysLogEx> _sysLogExRep; // 异常日志

    public DbLoggingWriter(IRepository<SysLogOp> sysLogOpRep,
        IRepository<SysLogEx> sysLogExRep)
    {
        _sysLogOpRep = sysLogOpRep;
        _sysLogExRep = sysLogExRep;
    }

    public void Write(LogMessage logMsg, bool flush)
    {
        if (logMsg.LogLevel == Microsoft.Extensions.Logging.LogLevel.Information)
        {
            if (logMsg.LogName == "SysLogDbAudit")
            {
                return;
            }
            _sysLogOpRep.InsertNow(new SysLogOp
            {
                LogName = logMsg.LogName,
                LogLevel = logMsg.LogLevel.ToString(),
                EventId = logMsg.EventId.ToString(),
                Message = logMsg.Message,
                Exception = logMsg.Exception == null ? "" : JSON.Serialize(logMsg.Exception),
            });
        }
        else if (logMsg.LogLevel == Microsoft.Extensions.Logging.LogLevel.Error)
        {
            //if (logMsg.Message != null)
            //{
            //    if (logMsg.Message == "未找到用户，请先进行绑定")
            //    {
            //        return;
            //    }
            //}

            _sysLogExRep.InsertNow(new SysLogEx
            {
                LogName = logMsg.LogName,
                LogLevel = logMsg.LogLevel.ToString(),
                EventId = logMsg.EventId.ToString(),
                Message = logMsg.Message,
                Exception = logMsg.Exception == null ? "" : JSON.Serialize(logMsg.Exception),
            });
        }
    }
}

